<template>
  <div style="padding: 10px 30px">
    <el-select
      v-model.trim="queryForm.group"
      clearable
      filterable
      :placeholder="'请选择组别'"
      style="width: 168px; padding: 0 10px"
      @change="selectData"
    >
      <el-option v-for="(item, index) in groups" :key="index" :label="item.group_id" :value="item.group_id" />
    </el-select>
    
    <el-select
      v-if="queryForm.group"
      v-model.trim="queryForm.name"
      clearable
      filterable
      :placeholder="'快速搜索学生'"
      style="width: 168px; padding: 0 10px"
      @change="selectData"
    >
      <el-option v-for="(item, index) in students" :key="index" :label="item.name" :value="item.name" />
    </el-select>
    <el-button v-if="queryForm.group" :disabled="isLoading" :icon="Search" native-type="submit" type="success" @click="lastData">
      上一组
    </el-button>
    <!-- <el-button :disabled="isLoading" :icon="Search" native-type="submit" type="primary" @click="selectData">查询</el-button> -->
    <el-button v-if="queryForm.group" :disabled="isLoading" :icon="Search" native-type="submit" type="success" @click="nextData">
      下一组
    </el-button>
    <el-input placeholder="请输入准考证号" clearable v-model="queryForm.bracelet_number" style="width:200px;margin:0 10px"></el-input>
    <el-button :disabled="isLoading" :icon="Search" native-type="submit" type="success" @click="searchData">
      搜索
    </el-button>
    <el-button v-if="queryForm.group && !isclient" :disabled="isLoading" :icon="Search" native-type="submit" type="primary" @click="prints">
      打印成绩
    </el-button>
    <!-- <el-button
      v-if="queryForm.group && !isclient"
      :disabled="isLoading"
      :icon="Search"
      native-type="submit"
      type="danger"
      @click="transfer"
    >
      上传成绩
    </el-button> -->
    <el-button v-if="isclient" :disabled="isLoading" :icon="Search" native-type="submit" type="warning" @click="read_this_card">
      读卡测试
    </el-button>
    <el-button v-if="isclient" :disabled="isLoading" :icon="Search" native-type="submit" type="success" @click="read_this_card_select">
      读卡并查询
    </el-button>
    <el-button
      v-if="queryForm.bracelet_number && queryForm.group && isclient"
      :disabled="isLoading"
      :icon="Search"
      native-type="submit"
      type="primary"
      @click="selectData"
    >
      返回
    </el-button>
  </div>
  <el-row class="data-screen-bottom">
    <el-col v-for="(item, i) in students" :span="4">
      <el-row>
        <el-col>
          <el-image class="data-screen-bottom-icon" :src="item&&item.avatar?item.avatar:bottom_01" style="width: 100px; height: 100px" @click="ChooseStudent(item.id)" />
          <h3 style="text-align: center" @click="ChooseStudent(item.id)">
            {{ item.name }}
            <span v-if="item.project_1_achievement && item.project_2_achievement && item.project_3_achievement">【完】</span>
          </h3>
        </el-col>
      </el-row>
    </el-col>
  </el-row>

  <el-dialog
    v-if="currentStudent.id"
    v-model="currentStudent"
    align-center
    :title="currentStudent.name + '[' + currentStudent.basic_sex_T_sex.name + ']'"
    width="500"
  >
  <el-row>
    <el-col :span="8">
      <el-image 
        :src="currentStudent&&currentStudent.avatar?currentStudent.avatar:bottom_01" 
        style="width: 100px; height: 100px" 
      />
    </el-col>
    <el-col :span="16">
      <div>考号：{{ currentStudent.student_code }}</div>
      <div style="color:green" v-if="currentStudent.is_hk == '2'">缓考</div>
      <div style="color:red" v-if="currentStudent.is_bk == '2'">补考</div>
      <div v-if="currentStudent.test_score > 0">测试总分：{{ currentStudent.test_score }}</div>

      <div v-if="currentStudent.sport_zk_standard_project_T_project_1">
        {{ currentStudent.sport_zk_standard_project_T_project_1.name }}：{{ currentStudent.project_1_achievement }} ({{
          currentStudent.project_1_score > 0 ? currentStudent.project_1_score + '分' : '尚未测试'
        }})
      </div>
      <div v-if="currentStudent.sport_zk_standard_project_T_project_2">
        {{ currentStudent.sport_zk_standard_project_T_project_2.name }}：{{ currentStudent.project_2_achievement }} ({{
          currentStudent.project_2_score > 0 ? currentStudent.project_2_score + '分' : '尚未测试'
        }})
      </div>
      <div v-if="currentStudent.sport_zk_standard_project_T_project_3">
        {{ currentStudent.sport_zk_standard_project_T_project_3.name }}：{{ currentStudent.project_3_achievement }} ({{
          currentStudent.project_3_score > 0 ? currentStudent.project_3_score + '分' : '尚未测试'
        }})
      </div>

      <div>考试记录：</div>
      <div v-for="(log, index) in currentStudent.exam_log" :key="index">
        {{ log.project_name }} - 成绩：{{ log.achievement }} - 分数：{{ log.score }} - ({{ log.createtime }})
      </div>
    </el-col>
  </el-row>

  <template #footer>
    <div class="dialog-footer">
      <el-button @click="update(currentStudent.id)">更新数据（补考、项目变更）</el-button>
      <el-button @click="ruchang(currentStudent.id)">手动入场</el-button>
      <el-button @click="currentStudent.id = false">取消</el-button>
      <el-button v-if="isclient" type="primary" @click="write_this_card(currentStudent)">写卡</el-button>
      <el-button v-if="isclient" type="warning" @click="read_this_card()">读卡测试</el-button>
    </div>
  </template>
</el-dialog>
</template>

<script lang="ts" setup>
import { random } from 'lodash-es'
import bottom_01 from '/@/assets/data_screen_images/bottom_02_gray.png'

import { api, api_detail } from '/@/api/obj'
import { is_client, read_card, write_card } from '/@/api/scanCard'
import {
  api_getGroups,
  api_getStudentDetail,
  api_getStudents,
  api_rychang,
  api_bukao,
  api_uploadStudents,
  getStudentsPrints,
} from '/@/api/zkDataScreen'

defineOptions({
  name: 'DataScreenBottom',
})

const props = defineProps({
  exam_id: {
    type: Number,
    default: 0,
  },
})

const emit = defineEmits(['setGroup'])

const isclient = ref<boolean>(false) //当前是否是客户端

const queryForm = ref({
  group: '',
  exam_id: 0,
  name: '',
  id: 0, //student_id
  bracelet_number: '', //手环号
  student_key:'',
})

//弹框
const currentStudent = ref({
  idcard: '',
})

//年级
const groups = ref([])
//学生
const students = ref([])
const $baseConfirm = inject<any>('$baseConfirm')
const transfer = () => {
  //上传成绩
  // $baseMessage('即将对接......', 'error', 'hey')

  $baseConfirm('您确定要上传吗', null, async () => {
    const { msg }: any = await api_uploadStudents({ exam_id: queryForm.value.exam_id, group: queryForm.value.group })
    $baseMessage(msg, 'success', 'hey')
  })
}

//打印
// import { ElMessageBox } from 'element-plus'
import { ElLoading } from 'element-plus'
import VabPrint from '/@/plugins/VabPrint'
const prints = async () => {
  console.log('根据组别，搜索对应的students')
  console.log(queryForm.value)
  queryForm.value.exam_id = props.exam_id

  if (!queryForm.value.group) {
    // $baseMessage('请选择组别', 'error', 'hey')
    return false
  }
  const res = await getStudentsPrints(queryForm.value)
  const student = res.data.students

  let content = '<style>table,table tr th, table tr td {border-collapse: collapse; }</style>'
  content += '<table style="width:100%;" border=1 >'
  content += '<tr>'
  content += '<th colspan="17">'
  content += res.data.title
  content += '</th>'
  content += '<tr>'

  content += '<tr><td>姓名</td><td>报名号</td><td>测试总分</td><td>第一类</td><td>第二类</td><td>第三类</td><td>签字</td><tr>'

  for (let i = 0; i < student.length; i++) {
    content += '<tr>'
    content += `<td>${student[i].name}</td>`
    content += `<td>${student[i].student_code}</td>`
    content += `<td>${student[i].test_score} 分</td>`
    content += `<td>${student[i].sport_zk_standard_project_T_project_1 ? `${student[i].sport_zk_standard_project_T_project_1.name}:` : ''}  ${student[i].project_1_achievement}（${student[i].project_1_score > 0 ? `${student[i].project_1_score}分` : '尚未考试'}）</td>`
    content += `<td>${student[i].sport_zk_standard_project_T_project_2 ? `${student[i].sport_zk_standard_project_T_project_2.name}:` : ''}  ${student[i].project_2_achievement}（${student[i].project_2_score > 0 ? `${student[i].project_2_score}分` : '尚未考试'}）</td>`
    content += `<td>${student[i].sport_zk_standard_project_T_project_3 ? `${student[i].sport_zk_standard_project_T_project_3.name}:` : ''}  ${student[i].project_3_achievement}（${student[i].project_3_score > 0 ? `${student[i].project_3_score}分` : '尚未考试'}）</td>`
    content += `<td height="40px" width="160px"></td>`
    content += '<tr>'
  }

  content += '</table>'
  //获取所有学生
  // api_getStudents（

  VabPrint(content)

  // ElMessageBox.prompt('', '打印预览', {
  //   inputType: 'textarea',
  //   inputValue: content,
  //   inputErrorMessage: 'Invalid Email',
  //   confirmButtonText: '打印',
  //   draggable: true,
  // })
  //   .then(({ value }) => {
  //     console.log(value)
  //     VabPrint(value)
  //   })
  //   .catch(() => {})
}

const countConfig1 = reactive({
  startValue: 0,
  endValue: random(1000, 2000),
})

const countConfig2 = reactive({
  startValue: 0,
  endValue: random(1000, 2000),
})

const countConfig3 = reactive({
  startValue: 0,
  endValue: random(1000, 2000),
})

const countConfig4 = reactive({
  startValue: 0,
  endValue: random(1000, 2000),
})

useIntervalFn(() => {
  countConfig1.endValue = countConfig1.endValue + random(0, 100)
  countConfig2.endValue = countConfig2.endValue + random(0, 100)
  countConfig3.endValue = countConfig3.endValue + random(0, 100)
  countConfig4.endValue = countConfig4.endValue + random(0, 100)
}, 1000 * 5)

//写卡
const write_this_card = (row: any) => {
  console.log(row.bracelet_number)
  const tnum = write_card(row.bracelet_number)
  console.log(tnum)
  api('sport_zk_student', 'write_card', 'get', { bracelet_number: row.bracelet_number })
}

//读卡
const $baseMessage = inject<any>('$baseMessage')
const read_this_card = async () => {
  const { bracelet_number }: any = await read_card()
  console.log(bracelet_number)
  //根据手环号到系统中查询学生信息
  // $baseMessage(`CES`, 'success', 'hey')
  const { detail }: any = await api_detail('sport_zk_student', { exam_id: queryForm.value.exam_id, bracelet_number: bracelet_number })
  console.log(detail)
  if (detail) {
    if (currentStudent.value.idcard) {
      //表示有当前用户
      if (currentStudent.value.idcard != detail.idcard) {
        $baseMessage(`${detail.name} ${detail.idcard}`, 'error', 'hey')
        return false
      }
    }

    $baseMessage(`${detail.name} ${detail.idcard}`, 'success', 'hey')
  } else {
    $baseMessage(`手环未写入`, 'error', 'hey')
  }

  // $baseMessage(name, 'success', 'hey')
}

const ruchang = (student_id) => {
  console.log('入场')
  $baseConfirm('您确定要手动入场吗', null, async () => {
    const { msg }: any = await api_rychang({ student_id: student_id })
    $baseMessage(msg, 'success', 'hey')
  })
}

const searchData = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  const res = await api_getStudents(queryForm.value)
  console.log(res)
  students.value = res.data
  loading.close()
 }

const update = (student_id) => {
  console.log('更新补考数据')
  $baseConfirm('您确定要更新数据吗', null, async () => {
    const { msg,data }: any = await api_bukao({ student_id: student_id })
    console.log(data)
    if(data.data && data.data.is_bk){
      currentStudent.value = data.data
      searchData()
      $baseMessage(msg, 'success', 'hey')
    }else{
      $baseMessage(msg, 'error', 'hey')
    }
  })
}


//读卡并查询
const read_this_card_select = async () => {
  const { bracelet_number }: any = await read_card()
  console.log(bracelet_number)
  //根据手环号到系统中查询学生信息
  queryForm.value.bracelet_number = bracelet_number
  const res = await api_getStudents(queryForm.value)
  students.value = res.data
  // queryForm.value.bracelet_number = ''

  // $baseMessage(name, 'success', 'hey')
}

//查看数据
const ChooseStudent = async (id: any) => {
  queryForm.value.id = id
  const res = await api_getStudentDetail(queryForm.value)
  currentStudent.value = res.data
}
//查看数据
const selectData = async () => {
  queryForm.value.bracelet_number = ''
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  //根据年级id，班级id，搜索对应的students
  console.log('根据组别，搜索对应的students')
  console.log(queryForm.value.group)
  queryForm.value.exam_id = props.exam_id

  console.log(queryForm.value.group)
  emit('setGroup', queryForm.value.group)
  if (!queryForm.value.group) {
    // $baseMessage('请选择组别', 'error', 'hey')
    loading.close()
    students.value = []
    return false
  }
  console.log(queryForm.value.group)
  const res = await api_getStudents(queryForm.value)
  console.log(res)
  students.value = res.data
  loading.close()
  // groups.value = res.data
  if (students.value.length == 0 && queryForm.value.group) {
    $baseMessage('该组暂无考生', 'error', 'hey')
  }
}
//下一组
const lastData = async () => {
  //根据年级id，班级id，搜索对应的students
  console.log('根据组别，搜索对应的students')
  console.log(queryForm.value.group)
  if (parseInt(queryForm.value.group) - 1 > 0) {
    queryForm.value.group = (parseInt(queryForm.value.group) - 1).toString()
    queryForm.value.exam_id = props.exam_id
    selectData()
  }

  // if (!queryForm.value.group) {
  //   // $baseMessage('请选择组别', 'error', 'hey')
  //   return false
  // }

  // const res = await api_getStudents(queryForm.value)
  // students.value = res.data
  // if (students.value.length == 0 && queryForm.value.group) {
  //   $baseMessage('该组暂无考生', 'error', 'hey')
  // }
  // groups.value = res.data
}
//下一组
const nextData = async () => {
  //根据年级id，班级id，搜索对应的students
  // console.log('根据组别，搜索对应的students')
  // console.log(queryForm.value.group)
  queryForm.value.group = (parseInt(queryForm.value.group) + 1).toString()
  queryForm.value.exam_id = props.exam_id
  selectData()
  // if (!queryForm.value.group) {
  //   $baseMessage('请选择组别', 'error', 'hey')
  //   return false
  // }

  // const res = await api_getStudents(queryForm.value)
  // students.value = res.data
  // if (students.value.length == 0 && queryForm.value.group) {
  //   $baseMessage('该组暂无考生', 'error', 'hey')
  // }
  // groups.value = res.data
}

onMounted(async () => {
  console.log(`left exam_id${props.exam_id}`)
  //根据exam_id获取有多少个年级
  const data = {
    exam_id: props.exam_id,
  }
  queryForm.value.exam_id = props.exam_id
  const res = await api_getGroups(data)

  groups.value = res.data
  isclient.value = is_client()
  // if (groups.value.length > 0) {
  //   queryForm.value.exam_id = props.exam_id
  //   queryForm.value.group = groups.value[0]
  //   const res = await api_getStudents(queryForm.value)
  //   students.value = res.data
  // }

  //之前有学生需要写卡的这个逻辑，现在取消了
  // setInterval(async function () {
  //   if (!currentStudent.value.id) {
  //     const res = await api('sport_zk_student', 'get_need_write', 'get', {
  //       exam_id: queryForm.value.exam_id,
  //       group_id: queryForm.value.group,
  //     })
  //     if (res && res.data) {
  //       //表示有正在进行的学生
  //       currentStudent.value = res.data
  //       console.log('ruchang', currentStudent.value)
  //     }
  //   } else {
  //     console.log('ruchang11', res)
  //   }
  // }, 3000)
})
</script>

<style lang="scss" scoped>
.data-screen-bottom {
  display: flex;
  align-items: left;
  justify-content: left;
  height: 100%;

  &-icon {
    display: block;
    width: 140px;
    height: 140px;
    padding: 20px;
    margin: 8px auto 0 auto;
    background: #101f58;
    border-radius: 50%;
    animation: twink 3s linear infinite;
  }

  &-text {
    margin-top: 10px;
    font-size: 30px;
    color: #64c5d9;
    text-align: left;

    p {
      font-size: 14px;
      color: #fff;
    }
  }
}
</style>
